package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.schedule.file.utils.common.AppJwtUtil;
import com.zhentao.schedule.model.common.dtos.ResponseResult;
import com.zhentao.schedule.model.common.enums.AppHttpCodeEnum;

import com.zhentao.dto.WmLoginDto;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.pojo.WmUser;
import com.zhentao.service.WmUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2024/2/24 8:59
 * @Author xdm
 **/
@Service
public class WmUserServiceImpl implements WmUserService {

    @Autowired
    private WmUserMapper wmUserMapper;

    @Override
    public ResponseResult login(WmLoginDto dto) {

        //1.进行判空操作，后台系统不允许游客登录
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码为空");
        }

        //2.根据用户名查询用户是否存在
        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmUser::getName, dto.getName());
        WmUser wmUser = wmUserMapper.selectOne(queryWrapper);

        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号不存在");
        }

        //3.对比密码
        String slat = wmUser.getSalt();
        String pwd = dto.getPassword();
        String md5Pwd = DigestUtils.md5DigestAsHex((pwd + slat).getBytes());
        if (md5Pwd.equals(wmUser.getPassword())) {
            //登录成功，返回token
            String token = AppJwtUtil.getToken(wmUser.getId().longValue());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            wmUser.setPassword("");
            wmUser.setSalt("");
            map.put("user", wmUser);

            return ResponseResult.okResult(map);

        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误");
        }

    }

}
